using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CodeIn.Ui.Dock;
using System.IO;
using CodeIn.Diagnostics;
using Mvvm;
using System.ComponentModel;
using AurelienRibon.Ui.SyntaxHighlightBox;

namespace CodeIn.Modules.Ui.Edit {
	public partial class EditView : UserControl, INotifyPropertyChanged {
		public PanelViewModel TabItemVmReference { get; set; }

		private string filePath;
		public string FilePath {
			get { return filePath; }
			set {
				filePath = value;
				if (editBox != null)
					editBox.Text = File.ReadAllText(value);
				string ext = System.IO.Path.GetExtension(value);
				switch (ext) {
					case ".vhd": editBox.CurrentHighlighter = HighlighterManager.Instance.Highlighters["VHDL"]; break;
					case ".vhdl": editBox.CurrentHighlighter = HighlighterManager.Instance.Highlighters["VHDL"]; break;
				}
				FirePropertyChanged("FilePath");
			}
		}

		public EditView() {
			InitializeComponent();
			DataContext = this;

			editBox.TextChanged += (s, e) => {
				if (TabItemVmReference != null)
					TabItemVmReference.IsSaved = false;
			};
		}

		private void Save() {
			try {
				File.WriteAllText(FilePath, editBox.Text);
				if (TabItemVmReference != null)
					TabItemVmReference.IsSaved = true;
			} catch (IOException ex) {
				MessageHandlers.Trace.WriteErrorLine(ex.Message);
			}
		}
		
		// --------------------------------------------------------------------
		// Commands
		// --------------------------------------------------------------------

		private RelayCommand saveCommand;
		public ICommand SaveCommand {
			get {
				if (saveCommand == null)
					saveCommand = new RelayCommand(
						p => { Save(); },
						p => true);
				return saveCommand;
			}
		}

		// --------------------------------------------------------------------
		// INotifyPropertyChanged
		// --------------------------------------------------------------------

		public event PropertyChangedEventHandler PropertyChanged;
		private void FirePropertyChanged(string propertyName) {
			if (PropertyChanged != null)
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}
	}
}
